﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.IsolatedStorage;
using System.Xml;
using System.Xml.Serialization;
using Microsoft.Xna.Framework;
using MainGame.GamePlay;
using Microsoft.Xna.Framework.GamerServices;

namespace MainGame.SaveData
{
  /// <summary>
  /// Information about the settings
  public struct Configuration
  {
    public float sfxVolume;
    public bool sfxMuted;
    public float musicVolume;
    public bool musicMuted;
    public Backgrounds chosenBackground;
    public Decks chosenDeck;

    public bool hasSavedGame;

    public int PlayerTurn;
    public GamePage currentPage;
  }

  /// <summary>
  /// Information about a saved game
  /// </summary>
//  public class SavedGame
//  {
//    public float timeElapsed;
//    public GamePlay.IBoardState state;

//    public bool IsValid()
//    {
//      // Checks the conditions for a valid saved game
//      if (timeElapsed > 0)
//        return true;
//      return false;
//    }
//    public bool HasSavedGame()
//    {
//      string saveFilePath = Path.Combine("Scopa", "SavedGame.car");
//#if WINDOWS || XBOX
//          if (File.Exists(saveFilePath))
//            return true;
//#else
//      IsolatedStorageFile appStorage = IsolatedStorageFile.GetUserStoreForApplication();
//      if (appStorage.FileExists(saveFilePath))
//        return true;
//#endif

//      return false;
//    }
//  }

  /// <summary>
  /// Provides functions to access data saved on disk
  /// </summary>
  static public class SaveUtils
  {
    static public Configuration defaultConfig = new Configuration { sfxVolume = 1.0f, sfxMuted = false, musicVolume = 1.0f, musicMuted = false, chosenDeck = Decks.Siciliane, chosenBackground = Backgrounds.Tovaglia, hasSavedGame = false, currentPage = GamePage.main };

    /// <summary>
    /// Saves a user configuration
    /// </summary>
    /// <param name="game">The current game</param>
    /// <param name="config">The configuration to save</param>
    static public void SaveConfig(this Game game, Configuration config)
    {
      XmlSerializer serializer = new XmlSerializer(typeof(Configuration));
      string configFile = "Config.car";

#if WINDOWS || XBOX
      //if (!Directory.Exists(saveDir))
      //  // No profiles created yet: create the profiles directory
      //  Directory.CreateDirectory(saveDir);
      //if (!Directory.Exists(configDir))
      //  // The profile is new: create the profile sub-directory
      //  Directory.CreateDirectory(configDir);
      StreamWriter writer = new StreamWriter(configFile);

#else
      IsolatedStorageFile appStorage = IsolatedStorageFile.GetUserStoreForApplication();
      // Replace the existing saved configuration with the new one
      if (appStorage.FileExists(configFile))
        appStorage.DeleteFile(configFile);
      IsolatedStorageFileStream streamFile = appStorage.OpenFile(configFile, FileMode.OpenOrCreate);
      StreamWriter writer = new StreamWriter(streamFile);

#endif
      serializer.Serialize(writer, config);
      writer.Close();
    }

    /// <summary>
    /// Loads a user configuration
    /// </summary>
    /// <param name="game">The current game</param>
    static public Configuration LoadConfig(this Game game)
    {
      XmlSerializer serializer = new XmlSerializer(typeof(Configuration));
      string configFile = "Config.car";

#if WINDOWS || XBOX
      // If the requested configuration doesn't exists, return default configuration
      if (!File.Exists(configFile))
        return defaultConfig;

      FileStream filestream = new FileStream(configFile, FileMode.OpenOrCreate);

#else
      IsolatedStorageFile appStorage = IsolatedStorageFile.GetUserStoreForApplication();
      // If the requested configuration doesn't exists, return default configuration
      if (!appStorage.FileExists(configFile))
        return defaultConfig;
      IsolatedStorageFileStream filestream = appStorage.OpenFile(configFile, FileMode.Open, FileAccess.Read);

#endif
      // Deserialize the XML file 
      Configuration config = (Configuration)serializer.Deserialize(filestream);
      filestream.Close();
      return config;
    }

    /// <summary>
    /// Saves the game
    /// </summary>
    /// <param name="game">The current game</param>
    /// <param name="config">The game to save</param>
    static public void SaveGame(this Game game, GamePlay.BoardState savedState)
    {
      //var state = (GamePlay.IBoardState)savedState;
      XmlSerializer serializer = new XmlSerializer(typeof(GamePlay.BoardState));

      string saveGameFile = "SavedGame.car";

#if WINDOWS || XBOX
      //if (!Directory.Exists(saveDir))
      //  // No profiles created yet: create the profiles directory
      //  Directory.CreateDirectory(saveDir);
      //if (!Directory.Exists(saveDir))
      //  // The profile is new: create the profile sub-directory
      //  Directory.CreateDirectory(saveDir);
      StreamWriter writer = new StreamWriter(saveGameFile);

#else
      IsolatedStorageFile appStorage = IsolatedStorageFile.GetUserStoreForApplication();
      // If this is the first game being saved, create the profiles directory
      //if (!appStorage.DirectoryExists(saveDir))
      //  appStorage.CreateDirectory(saveDir);

      // Replace the existing saved game with the new one
      if (appStorage.FileExists(saveGameFile))
        appStorage.DeleteFile(saveGameFile);

      IsolatedStorageFileStream streamFile = appStorage.OpenFile(saveGameFile, FileMode.CreateNew);
      StreamWriter writer = new StreamWriter(streamFile);

#endif
      serializer.Serialize(writer, savedState);
      writer.Close();
    }

    /// <summary>
    /// Loads a saved game
    /// </summary>
    /// <param name="game">The current game</param>
    /// <param name="id">The id number of the user</param>
    static public GamePlay.BoardState LoadGame(this Game game)
    {
      XmlSerializer serializer = new XmlSerializer(typeof(GamePlay.BoardState));
      string savedGameFile = "SavedGame.car";

#if WINDOWS || XBOX
      // If the requested saved game doesn't exists, return default saved game (empty)
      if (!File.Exists(savedGameFile))
        return null;
      FileStream filestream = new FileStream(savedGameFile, FileMode.OpenOrCreate);

#else
      IsolatedStorageFile appStorage = IsolatedStorageFile.GetUserStoreForApplication();
      // If the requested saved game doesn't exists, return default saved game (empty)
      //if (!appStorage.DirectoryExists(saveDir) || !appStorage.FileExists(savedGameFile))
      //  return null;
      IsolatedStorageFileStream filestream = appStorage.OpenFile(savedGameFile, FileMode.Open, FileAccess.Read);

#endif

      GamePlay.BoardState savedGame = (GamePlay.BoardState)serializer.Deserialize(filestream);
      filestream.Close();
      return savedGame;
    }


    /// <summary>
    /// Deletes a saved game
    /// </summary>
    /// <param name="game">The current game instance</param>
    static public void DeleteGame(this Game game)
    {
      XmlSerializer serializer = new XmlSerializer(typeof(GamePlay.BoardState));

      string saveGameFile = "SavedGame.car";

#if WINDOWS || XBOX
      // If the requested saved game doesn't exists, return
      if (!Directory.Exists(saveDir) || !File.Exists(saveGameFile))
        return;
      File.Delete(saveGameFile);

#else
      IsolatedStorageFile appStorage = IsolatedStorageFile.GetUserStoreForApplication();
      // If the requested saved game doesn't exists, return
      if (!appStorage.FileExists(saveGameFile))
        return;
      appStorage.DeleteFile(saveGameFile);

#endif

    }

  }
}
